<?php
/**
 * 用户类
 * @copyright 许雷
 * @since v1.0,
 * */
class myuser{
	private static $nickName;
	private static $money; //P币
	private static $encryPasswd; //加密过的用户密码
	private static $passwordKey = 'd2s*a$f^13)4=3-1+4Y^^&&Z2#4a%3vafd'; //用户密码私钥
	private static $safeCookieKey = '19*8*a$f^1t)4=R-o+f3^^&&d2#$#%@aKMd'; //cookie私钥
	private   $db; //数据库链接

	function __construct($db){
		$this->db = $db;
	}
    
    public static function createByRandId($randId,$db=null){
            if(!$db)$db = new mydb();
            $user = array(
                'FRandId'=>$randId,
                'FTime'=>date('Y-m-d H:i:s'),
                'FIp'=>myrequest::getIP()
            );
            $db->insert('tbl_user',$user);
            return $db->getInsertId();
    }
    
	/**
	 * 获取用户年龄
	 * @return $age
	 * */
	function getInfo(){
		return $this->userinfo ;
	}

	/**
	 * 设置用户年龄
	 * @return $age
	 * */
	function setInfo(){
		$this->userName = 'test';
		$this->password = '111';
	}

	public function setPassword( $password ){
		md5($key.$password);
	}

	public function getPaword(){

		return $this->password;
	}

	/**
	 * 设置用户名称
	 * */
	function setName($name){
		$this->userName = $name;
	}

	/**
	 * 获取用户名称
	 * @return String $name
	 * */
	public  static function getNick(){
		if(self::isLogin()){
			self::$nickName = c('nick');
			return self::$nickName;
		}else{
			return '匿名';
		}
	}

	/**
	 * 获取经过私钥加密过的密码
	 * @param $srcPassword 明文的密码
	 * */
	private function getSafePassword($srcPassword){
		return md5(self::$passwordKey . $srcPassword);
	}

	/**
	 * 更新用户的登录状态
	 * */
	private function updateLoginStatus($uid){
		$loginStatus = array(
		'FLastLoginTime'=>date('Y-m-d H:i:s'),
		'FLastIp'       =>$_SERVER['REMOTE_ADDR']
		);
		$this->db->update('tbl_user',$loginStatus,' FUserId='.intval($uid));
	}

	/**
	 * 实现用户登录
	 * @param $email
	 * @param $password
	 * @param $expire 过期时间，默认为1年时间
	 * */
	public function login($email, $password,$expire=31536000){
		$sql = 'SELECT * FROM tbl_user WHERE FEmail = "'.$email.'" ';
		$result = $this->db->query($sql);

		if(empty($result)){
			return false;
		}
		

		if($result[0]['FPassword'] != $this->genPwd($result[0]['FNick'],$password)){
			return false;
		}

		//更新登录状态
		$this->updateLoginStatus($result[0]['FUserId']);

		$uid  = $result[0]['FUserId'];
		$nick = $result[0]['FNick'];
		$time = time();
		$money = $result[0]['FMoney'];

		$time = time() + $expire;
		//设置cookie
		setcookie('uid' , $uid,$time,'/','.polang.org');
		setcookie('nick', $nick,$time,'/','.polang.org');
		setcookie('time', $time,$time,'/','.polang.org');
		setcookie('c' , $this->getSafeCookie($uid,$nick,$time,$money),$time,'/','.polang.org');
		setcookie('m' , $money,$time,'/','.polang.org');
		return true;
	}

	/**
	 * 不带密码强制登录
	 * */
	public function forceLogin($email,$expire=3600){
		$sql = 'SELECT * FROM tbl_user WHERE FEmail = "'.$email.'" ';
		$result = $this->db->query($sql);
		//更新登录状态
		$this->updateLoginStatus($result[0]['FUserId']);
		$uid  = $result[0]['FUserId'];
		$nick = $result[0]['FNick'];
		$time = time();
		$money = $result[0]['FMoney'];

		$time = time() + $expire;
		//设置cookie
		setcookie('uid' , $uid,$time,'/','.polang.org');
		setcookie('nick', $nick,$time,'/','.polang.org');
		setcookie('time', $time,$time,'/','.polang.org');
		setcookie('c' , $this->getSafeCookie($uid,$nick,$time,$money),$time,'/','.polang.org');
		setcookie('m' , $money,$time,'/','.polang.org');
		return true;

	}


	/**
	 * 退出登录
	 * */
	public static  function logout(){
		//设置cookie
		setcookie('uid' , '',0,'/','.polang.org');
		setcookie('nick', '',0,'/','.polang.org');
		setcookie('time', '',0,'/','.polang.org');
		setcookie('c' , '',0,'/','.polang.org');
		setcookie('m' , '',0,'/','.polang.org');
		return true;
	}

	/**
	 * 获取安全的登录态字符串，避免伪造cookie登录
	 * 
	 * */
	public static  function getSafeCookie($uid,$nick,$time,$money){
		$timeKey = self::getTimeKey($time);
		return md5(self::$safeCookieKey.$uid.$nick.$timeKey.$money);
	}

	/**
	 * 根据时间生产时间key
	 * */
	private static  function getTimeKey($time){
		return fmod($time,500);
	}

	/**
	 * 检查回传过来的安全cookie是否正确
	 * 
	 */
	public  static function checkSafeCookie($uid,$clientNick,$clientTime,$clientMoney,$clientKey){
		$timeKey = self::getTimeKey($clientTime);
		if($clientMoney == ''){
			return false;
		}

		if($clientTime == ''){
			return false;
		}

		if($clientNick == ''){
			return false;
		}

		if($clientKey == self::getSafeCookie($uid,$clientNick,$clientTime,$clientMoney)){
			return true;
		}

		return false;
	}

	/**
	 * 判断当前用户是否登录
	 * */
	public static  function isLogin(){
		$time = c('time');
		if(intval($time) < 10000){//时间不正确
			return false;
		}



		/*		if(time() - $time > 3600 *24 * 60 ){//登录超过两个月时间，@todo bug
		return false;
		}*/

		$uid  = intval(c('uid'));
		$nick = c('nick');
		$clientKey = c('c');
		$clientMoney = c('m');
		if(self::checkSafeCookie($uid,$nick,$time,$clientMoney,$clientKey)){
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 检查email是否已经在数据库存在
	 * */
	public function existEmail($email){
		if($this->db->getCount('tbl_user','FEmail="'.$email.'" ') > 0){
			return true;
		}else {
			return false;
		}
	}
	/**
	 * 检查昵称是否已经在数据库存在
	 * */
	public function existNick($nick){
		if($this->db->getCount('tbl_user','FNick="'.$nick.'" ') > 0){
			return true;
		}else {
			return false;
		}
	}



	/**
	 * 注册新用户
	 * 
	 * */
	public function insert($email,$password,$nick,$receiveEmail,$openIdQQ=''){
		$userInfo = array(
		'FEmail'    => $email,
		'FReceiveEmail' => $receiveEmail,
		'FMaxView'  => DEFAULT_MAX_VIEW,
		'FPassword' => $this->genPwd($nick,$password),
		'FNick'     => $nick,
		'FLastLoginTime' => date('Y-m-d H:i:s'),
		'FLastIp'   => myrequest::getIP(),
		'FOpenIdQQ' => $openIdQQ
		);
		if($this->db->insert('tbl_user',$userInfo)){
			$this->login($email,$password);
		}else{//注册失败
			mydispatch::to('user','reg');
		}
	}

	public static function getMoney(){
		if(self::isLogin()){
			self::$money = c('m');
			return self::$money;
		}else{
			return 0;
		}
	}

	/**
	 * 生产密码串
	 * */
	public function genPwd($nick,$srcPwd){
		$srcStr = strtolower(trim($nick)).'&6x2h5j8nny10N5O;6^lJO0oq,'.$srcPwd;
		return md5($srcStr);
	}
	
	/**
	 * 獲取顯示前臺用的用戶明
	 * */
	public static  function getShowName(){
		if(myopenqq::isLogin()){
			return myopenqq::getOpenName();
		}else {
			return myuser::getNick();
		}
	}

}
?>